package com.gxc.string;

import java.util.Arrays;

/**
 * 67. 二进制求和

 * 给你两个二进制字符串 a 和 b ，以二进制字符串的形式返回它们的和。
 */
public class AddBinary {

    public static void main(String[] args) {
        System.out.println(Arrays.toString(new Character[]{'a','b'}));
        StringBuffer str = new StringBuffer();
        str.append("a").append("b").append("c");
        System.out.println(str.toString());
        str.reverse();
        System.out.println(str.toString());

        System.out.println(handle("11", "1"));
        System.out.println(handle("1010", "1011"));
    }

    public static String handle(String a, String b) {
        int al = a.length()-1;
        int bl = b.length()-1;
        int c = 0;
        StringBuffer str = new StringBuffer();
        while (al>=0 && bl>=0) {
            int sum = a.charAt(al) - '0' + b.charAt(bl) - '0' + c;
            if (sum >1) {
                c = 1;
                str.append(sum%2);
            } else {
                c = 0;
                str.append(sum%2);
            }
            al--;
            bl--;
        }
        while (al>=0) {
            int sum = a.charAt(al) - '0' + c;
            if (sum >1) {
                c = 1;
                str.append(sum%2);
            } else {
                c = 0;
                str.append(sum%2);
            }
            al--;
        }
        while (bl>=0) {
            int sum = b.charAt(bl) - '0' + c;
            if (sum >1) {
                c = 1;
                str.append(sum%2);
            } else {
                c = 0;
                str.append(sum%2);
            }
            bl--;
        }
        if (c == 1) str.append(c);
        return str.reverse().toString();
    }


    class Solution {
        public String addBinary(String a, String b) {
            return java.lang.Integer.toBinaryString(
                    java.lang.Integer.parseInt(a, 2) + java.lang.Integer.parseInt(b, 2)
            );
        }
    }

}
